'use strict'

import mongoose from 'mongoose'
import robot from '../service/robot'
const User = mongoose.model('User')

exports.signature = (ctx, next) => {
  const body = ctx.request.body
  const cloud = body.cloud // 如果参数里有key说明是生成七牛签名
  let data

  if (cloud === 'qiniu') {
    data = robot.getQiniuToken(body)
  } else {
    data = robot.getCloudinaryToken(body)
  }

  ctx.body = {
    success: true,
    data: data
  }
}

exports.hasBody = async (ctx, next) => {
  const body = ctx.request.body || {}

  if (Object.keys(body).length === 0) {
    ctx.body = {
      success: false,
      err: '没有参数'
    }

    return next
  }

  await next()
}

exports.hasToken = async (ctx, next) => {
  let accessToken = ctx.query.accessToken

  if (!accessToken) {
    accessToken = ctx.request.body.accessToken
  }

  if (!accessToken) {
    ctx.body = {
      success: false,
      err: '钥匙丢了'
    }

    return next
  }

  let user = await User.findOne({
    accessToken: accessToken
  })

  if (!user) {
    ctx.body = {
      success: false,
      err: '用户没有登录'
    }

    return next
  }

  ctx.session = ctx.session || {}
  ctx.session.user = user

  await next()
}